<?php
header('Content-Type: text/html; charset=utf-8');
// 在后端获取前端表单数据的方法是使用全局数组 $_GET  $_POST
$userName = trim($_POST['userName']);
$pwd = trim($_POST['pwd']);
$cpwd = trim($_POST['cpwd']);
$sex = trim($_POST['sex']);
$fav = @implode(",",$_POST['fav']);
$email = trim($_POST['email']);

/*
echo "您输入的用户是:$userName<br>";
echo "您输入的密码是:$pwd<br>";
echo "您输入的确认是:$cpwd<br>";
echo "您输入的用户是:". $sex == 1?"男":"女" . "<br>";
echo "你选择的爱好是:" . implode(",", $fav);
*/

// 进行必要的验证
if(!strlen($userName) || !strlen($pwd)){
    echo "<script>alert('用户名或密码没有填写');history.back();</script>";
    exit;
}elseif(!preg_match('/^[a-zA-Z0-9]{3,10}$/',$userName)){
    echo "<script>alert('用户名必填，且只能由大小写字符和数字组成，长度在3到10个字符!');history.back();</script>";
    exit;
}elseif($pwd <> $cpwd){
    echo "<script>alert('密码和确认密码必须相同');history.back();</script>";
    exit;
}elseif (!preg_match('/^[a-zA-Z0-9_*]{6,10}$/',$pwd)){
    echo "<script>alert('密码必填,且只能大小写和数字,以及*_构成,长度为6到10个字符!');history.back();</script>";
    exit;
}elseif(!empty($email)){
    if(!preg_match("/^[a-zA-Z0-9_\-]+@[a-zA-Z0-9]+\.(com|cn|net|org)$/",$email)){
        echo "<script>alert('信箱格式不正确!');history.back();</script>";
        exit;
    }
}

include_once "conn.php";
// 判断用户名是否存在
$sql = "select * from user where userName = '$userName';";
$result = mysqli_query($conn,$sql);
var_dump($result);
$num = mysqli_num_rows($result);
echo $num;
if($num){
    echo "<script>alert('用户名已存在');history.back();</script>";
    exit;
}
// sql语句
$sql = "insert into user (userName,pwd,sex,email,fav,createTime) values 
        ('$userName','".md5($pwd)."','$sex','$email','$fav','".time()."')";

$result = mysqli_query($conn,$sql);
if($result){
    echo "<script>alert('数据插入成功');location.href='index.php';</script>";
}else {
    echo "<script>alert('数据插入失败');history.back();</script>";
}